﻿using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Channels;

namespace TheGame.Webservices
{
	//[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
	[ServiceBehavior(IncludeExceptionDetailInFaults = true, ConcurrencyMode = ConcurrencyMode.Single)]
	[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
	public partial class TheGameService : EngineInterfaceBase, ITheGameService, IDisposable
	{
		public TheGameService()
		{
			//DispatchRuntime.AutomaticInputSessionShutdown = false;
			if (Callback == null)
			{
				ITheGameServiceCallback cb = OperationContext.Current.GetCallbackChannel<ITheGameServiceCallback>();
				if (cb != null)
					Callback = cb;
			}
			OperationContext context = OperationContext.Current;
			MessageProperties messageProperties = context.IncomingMessageProperties;
			RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; 
			Console.WriteLine("Client connected from " + endpointProperty.Address);
			OperationContext.Current.Channel.Closed += ChannelClosed;
			OperationContext.Current.Channel.Faulted += ChannelFaulted;
		}
		
		void ChannelFaulted(object sender, EventArgs e)
		{
			Console.WriteLine("Client aborted connection.");
			ChannelClosed(sender, e);
		}

		void ChannelClosed(object sender, EventArgs e)
		{
			OperationContext context = OperationContext.Current;
			if (context != null)
			{
				MessageProperties messageProperties = context.IncomingMessageProperties;
				RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
				Console.WriteLine("Client disconnected from " + endpointProperty.Address);
			}
			Callback = null;

			if(_heartbeatTimer != null)
			{
				_heartbeatTimer.Close();
				_heartbeatTimer = null;
			}
			if (Db != null)
				Db.Close();
			Db = null;
		}

		public void ServiceConnect()
		{}

		public void Dispose()
		{
		}
	}
}